﻿using System;
using System.Windows;
using System.Windows.Media;
using _3DTicTacToe.Core;

namespace _3DTicTacToe
{
    public partial class NewGameDialog : Window
    {
        private readonly BrushList _brushList;
        private bool _playerOneValid, _playerTwoValid;
        bool AllValid { get { return _playerOneValid && _playerTwoValid; } }

        public NewGameDialog()
        {
            InitializeComponent();

            var rnd = new Random();
            firstPlayerCBox.SelectedIndex = rnd.Next(0, 2);

            _brushList = new BrushList();

            playerOneColorCBox.DataContext = _brushList;
            playerTwoColorCBox.DataContext = _brushList;

            playerOneNameTBox.IsValidNameChanged += PlayerOneNameTBoxIsValidNameChanged;
            playerOneNameTBox.LastValidNameChanged += playerOneNameTBox_LastValidNameChanged;

            playerTwoNameTBox.IsValidNameChanged += PlayerTwoNameTBoxIsValidNameChanged;
            playerTwoNameTBox.LastValidNameChanged += playerTwoNameTBox_LastValidNameChanged;

            startButton.IsEnabled = false;
        }

        void playerTwoNameTBox_LastValidNameChanged(string name)
        {
            playerTwoCBItem.Content = name;
        }

        void playerOneNameTBox_LastValidNameChanged(string name)
        {
            playerOneCBItem.Content = name;
        }

        void PlayerTwoNameTBoxIsValidNameChanged(bool valid)
        {
            _playerTwoValid = valid;
            startButton.IsEnabled = AllValid;
        }

        void PlayerOneNameTBoxIsValidNameChanged(bool valid)
        {
            _playerOneValid = valid;
            startButton.IsEnabled = AllValid;
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            var p1 = new Player(playerOneNameTBox.Text,
                                (Color)ColorConverter.ConvertFromString(playerOneColorCBox.SelectedItem as string));
            var p2 = new Player(playerTwoNameTBox.Text,
                                (Color)ColorConverter.ConvertFromString(playerTwoColorCBox.SelectedItem as string));

            var game = firstPlayerCBox.SelectedIndex == 0
                           ? new TicTacToeGame(p1, p2)
                           : new TicTacToeGame(p2, p1);

            new GameWindow(game).Show();
            Close();
        }
    }
}
